class YZEventBus {
  constructor() {
    this.eventBus = {}
  }

  on(eventName, eventFun, thisArg) {
    let handlers = this.eventBus[eventName];
    if(!handlers) {
      handlers = [];
      this.eventBus[eventName] = handlers;
    }
    handlers.push({
      eventFun,
      thisArg
    })
  }

  emit(eventName, ...payload) {
    let handlers = this.eventBus[eventName];
    if(!handlers) return;
    handlers.forEach(handler => {
      handler.eventFun.apply(handler.thisArg, payload);
    });
  }

  off(eventName, eventFun) {
    let handlers = this.eventBus[eventName];
    if(!handlers) return;
    const tempArr = [...handlers];
    for(let i = 0; i < tempArr.length; i++) {
      const handler = tempArr[i];
      if(handler.eventFun === eventFun) {
        const index = handlers.indexOf(handler);
        handlers.splice(index, 1);
      }
    }
  }

}

const eventBus = new YZEventBus();

// main.js
eventBus.on("abc", function(payload) {
  console.log("监听abc", this, payload);
}, {name: "yz"});

const handleCallback = function(payload) {
  console.log("监听abc", this, payload);
}

eventBus.on("abc", handleCallback, {name: "yz"});

// utils.js
eventBus.emit("abc", 123);

eventBus.off("abc", handleCallback);
eventBus.emit("abc", 123);



